//
// Created by Arikes on 9/22/21.
//

#ifndef DESIGNERMODE_FLYWEIGHTFACTORY_H
#define DESIGNERMODE_FLYWEIGHTFACTORY_H

#include <map>
#include <iostream>
#include "ConcreteFlyweight.h"
namespace FlyweightMode
{
    class FlyweightFactory
    {
    public:
        Flyweight* getFlyweight(std::string key)
        {
//            Flyweight flyweight = (Flyweight) flyweights.get(key);
//            if (flyweight != null) {
//                System.out.println("具体享元" + key + "已经存在，被成功获取！");
//            } else {
//                flyweight = new ConcreteFlyweight(key);
//                flyweights.put(key, flyweight);
//            }
//            return flyweight;

            auto itor_flyweight = _flyweights.find(key);
            if (itor_flyweight != _flyweights.end()){
                return itor_flyweight->second;
            }
            else
            {
                Flyweight *flyweight = new ConcreteFlyweight(key);
                _flyweights.insert(std::make_pair(key,flyweight));
                return flyweight;
            }
        }
    private:
        std::map<std::string,Flyweight*> _flyweights;
    };
}
#endif //DESIGNERMODE_FLYWEIGHTFACTORY_H

//FlyweightMode::FlyweightFactory* factory = new FlyweightMode::FlyweightFactory;
//FlyweightMode::Flyweight* fw01 = factory->getFlyweight("a");
//FlyweightMode::Flyweight* fw02 = factory->getFlyweight("a");
//FlyweightMode::Flyweight* fw03 = factory->getFlyweight("a");
//
//FlyweightMode::Flyweight* fw04 = factory->getFlyweight("b");
//FlyweightMode::Flyweight* fw05 = factory->getFlyweight("b");
//
//fw01->operation(FlyweightMode::UnsharedConcreteFlyweight("第1次调用a。"));
//fw02->operation(FlyweightMode::UnsharedConcreteFlyweight("第2次调用a。"));
//fw03->operation(FlyweightMode::UnsharedConcreteFlyweight("第3次调用a。"));
//fw04->operation(FlyweightMode::UnsharedConcreteFlyweight("第1次调用b。"));
//fw05->operation(FlyweightMode::UnsharedConcreteFlyweight("第2次调用b。"));